/*=====================================================
Critical Links
Auto Configuration Server

Authors:
	Rui Eduardo Gouveia Gil - r-gil@critical-links.com

Date: 2011
Version 0.1
=======================================================*/
DevicePanel = function(device,parent) {
	this.device = device;
	this.parent = parent;

    this.commands;

	this.deviceInformation = new Ext.Panel({
		layout: 'anchor',
        cls:'preview',
		border:false,
		region:'north',
		height: 350,
        minSize: 80,
        maxSize: 600,
        split: true,
        autoScroll: true,
        html: ''
    });

	this.logList = new Ext.grid.GridPanel({
        title: 'Devices contact log',
        region: 'center',
        border: false,
        split: true,
        columns: [{ header: 'Level', width: 60, renderer: this.renderLogLevel, dataIndex: 'Level', sortable: true, fixed: true},
        		  { header: "Time", dataIndex: 'Time', width: 120, sortable: true, fixed: true},
        		  { header: "Ip", dataIndex: 'Ip', width: 100, sortable: true, fixed: true},
        		  { header: "Release", dataIndex: 'Release', width: 120, sortable: true},
//        		  { header: "Command", dataIndex: 'Command', width: 100, sortable: true},
//        		  { header: "Result", dataIndex: 'Result', width: 120, sortable: true},
        		  { header: "Message", dataIndex: 'Message', width: 300, sortable: true}],
        store: new Ext.data.ArrayStore({fields: ['Level','Time','Ip','Release','Command','Result','Message','Log']})
    });

    this.logList.store.setDefaultSort('LastContactOn', "DESC");

    DevicePanel.superclass.constructor.call(this, {
        closable: true,
		layout: 'border',
    	autoDestroy: true,
        id: this.device.tid,
    	iconCls:'device-icon',
        title: this.device.text,
        tabTip: this.device.description,
        items: [this.deviceInformation,this.logList],
        loadMask: {msg:'Loading Feed...'},
		tbar:[{text:'Edit Device', tooltip: {title:'Edit a device.'}, iconCls: 'edit-device-icon', handler: this.showEditDevice, scope:this },
			  {text:'Wan setup', tooltip: {title:'Edit wan setup.'}, iconCls: 'wan-device-icon', handler: this.showWanDevice, scope:this },
			  {text:'Move Device', tooltip: {title:'Move the device to another group.'}, iconCls: 'move-device-icon', handler: this.showMoveDevice, scope:this },
			  {id: 'validated'+this.device.id, text:'Validade', tooltip: {title:'Validate.'}, iconCls: 'validate-device-icon', handler: this.validateDevice, scope:this},
			  //{id: 'backup'+this.device.id, text:'Request Backup', tooltip: {title:'Request Device Backup.'}, iconCls: 'backup-device-icon', handler: this.backupDevice, scope:this},
        	  {text:'Refresh', tooltip: {title:'Refresh'}, iconCls: 'refresh-list-icon', handler: this.refreshPanel, scope:this }]
    });

	this.addEvents({savedevice:true,moveDevice:true});

	this.getTopToolbar().items.get('validated'+this.device.id).setDisabled(true);
	
	this.on('close', this.onClose, this);
	this.task = Ext.TaskMgr.start({run: this.onTimer, interval: 60000, scope: this});
};

Ext.extend(DevicePanel, Ext.Panel, {	
	onClose : function(device) {
		Ext.TaskMgr.stop(this.task);
	},	

	refresh : function(device) {
		this.onTimer();
	},	

	showWanDevice : function(){
        if(!this.winWanDevice){
            this.winWanDevice = new DeviceWanWindow();
            this.winWanDevice.on('savewan', this.saveWan, this);
        }

        this.winWanDevice.show(this.device);
	},

	saveWan : function(){
 		SGui.getDevice(this.device.id,this.cbRefreshDevice,this);
        SGui.getDeviceCommands(this.device.id,this.cbDeviceCommands,this);        
	},

	showEditDevice : function(){
        if(!this.winDevice){
            this.winDevice = new DeviceWindow();
            this.winDevice.on('savedevice', this.vUpdateDevice, this);
        }

        this.winDevice.show(this.device);
	},

	vUpdateDevice : function(xml){
		var old = this.device;
		this.updateDevice(new Device(xml));
		this.parent.fireEvent('refreshtree');
		this.parent.fireEvent('refreshdevice',this.device,old);
	},

	showMoveDevice : function() {
        if(!this.winMove){
            this.winMove = new DeviceMoveWindow(this.device);
            this.winMove.on('moveDevice', this.moveDevice, this);
        }

        this.winMove.show();
	},	
	
	moveDevice : function() {
        this.parent.fireEvent('refresh');
        this.parent.fireEvent('refreshtree');
	},	

	validateDevice : function() {
		SGui.validateDevice(this.device.id,this.cbValidateDevice,this);	
	},

	backupDevice : function() {
		SGui.backupDevice(this.device.id,0,this.cbBackupDevice,this);	
	},
		
	cbValidateDevice : function(obj,result) {
		if(result) {	
			if(result instanceof Array) {			
				if(result[0] == '0' ) {
					Ext.MessageBox.show({title: 'Error', msg: result[1], buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.ERROR});
					
				} else {
					obj.device = new Device(result[1]);
					obj.updateDeviceHTML();
					obj.parent.fireEvent('refreshdevice',obj.device);
					
					obj.getTopToolbar().items.get('validated'+obj.device.id).setDisabled((obj.device.status != 0 && obj.device.status != 1));
					//obj.getTopToolbar().items.get('backup'+obj.device.id).setDisabled((obj.device.status == 2 || obj.device.status == 3 || obj.device.status == 5));
				}				
			} else {
				Ext.MessageBox.show({title: 'Error', msg: 'Protocol Error! Please check the logs for more information.', buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.ERROR});
			}
		}
	},
		
	cbBackupDevice : function(obj,result) {
		if(result) {	
			if(result instanceof Array) {			
				if(result[0] == '0' ) {
					Ext.MessageBox.show({title: 'Error', msg: result[1], buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.ERROR});
					
				} else {
					obj.device = new Device(result[1]);
					obj.updateDeviceHTML();
					obj.parent.fireEvent('refreshdevice',obj.device);
					
					obj.getTopToolbar().items.get('validated'+obj.device.id).setDisabled((obj.device.status != 0 && obj.device.status != 1));
					//obj.getTopToolbar().items.get('backup'+obj.device.id).setDisabled((obj.device.status == 2 || obj.device.status == 3 || obj.device.status == 5));
				}				
			} else {
				Ext.MessageBox.show({title: 'Error', msg: 'Protocol Error! Please check the logs for more information.', buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.ERROR});
			}
		}
	},	

	updateDevice : function(device) {
		this.device = device;
		this.updateDeviceHTML();
	},	

	onTimer : function() {
		SGui.getDeviceLogs(this.device.id,1,0,15,this.cbRefreshLogs,this);
		SGui.getDevice(this.device.id,this.cbRefreshDevice,this);
        SGui.getDeviceCommands(this.device.id,this.cbDeviceCommands,this);        
	},	

	updateLog : function(xml) {
		var log = new Log(xml);
		this.logList.store.loadData([[log.level,log.dateStr,log.ip,log.release,log.command,log.result,log.message,log]],true);
	},

	refreshPanel : function() {
		SGui.getDeviceLogs(this.device.id,1,0,20,this.cbRefreshLogs,this);
		if(this.logList.el)
			this.logList.el.mask('Loading Logs...', 'x-mask-loading');
		
		SGui.getDevice(this.device.id,this.cbRefreshDevice,this);	
		if(this.deviceInformation.el)
			this.deviceInformation.el.mask('Loading Logs...', 'x-mask-loading');
	},

	cbRefreshLogs : function(obj,result){
		obj.logList.store.removeAll();
		if(result) {	
			if(result instanceof Array) {			
				for(var i=0; i<result.length; i++)
					obj.updateLog(result[i]);
			} else {
				obj.updateLog(result);
			}
		}
		if(obj.logList.el)
			obj.logList.el.unmask();
	},	
	
	cbRefreshDevice : function(obj,result){
		if(result) {	
			if(result instanceof Array) {			
				if(result[0] == '0' ) {
					Ext.MessageBox.show({title: 'Error', msg: result[1], buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.ERROR});
					
				} else {
					obj.device = new Device(result[1]);
					obj.updateDeviceHTML();
					obj.getTopToolbar().items.get('validated'+obj.device.id).setDisabled((obj.device.status != 0 && obj.device.status != 1));
					//obj.getTopToolbar().items.get('backup'+obj.device.id).setDisabled((obj.device.status == 2 || obj.device.status == 3 || obj.device.status == 5));
				}				
			} else {
				Ext.MessageBox.show({title: 'Error', msg: 'Protocol Error! Please check the logs for more information.', buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.ERROR});
			}
		}
		if(obj.deviceInformation.el)
			obj.deviceInformation.el.unmask();
	},
	
	cbDeviceCommands : function(obj,result) {
   		obj.commands = new Array();

     	if(result) {
    		if(result instanceof Array) {
    			for(var i=0; i<result.length; i++)
    				obj.commands.push(new Command(result[i]));
    		} else {
    			obj.commands.push(new Command(result));
    		}
     	}
		
		obj.updateDeviceHTML();
    },
	
	updateDeviceHTML : function(){
		var html = "";
		
		html += "	<div style=\"padding: 10px 0px 0px 10px;\">"
		html += "		<div style=\"padding-top: 5px;\"><table><tr><td><img src=\"icons/edgebox.png\"/></td><td valign=\"middle\">&nbsp;&nbsp;<span class=\"headText\">"+this.device.name+"</span></td></tr></table></div>";
		html += "		<div style=\"padding-top: 10px;\"><span class=\"lableText\">Status:&nbsp;</span><span class=\"text\">"+this.device.statusStr+"</span></div>";
		html += "		<div style=\"padding-top: 5px;\"><span class=\"lableText\">Configuration:&nbsp;</span><span class=\"text\">"+this.device.configName+"</span></div>";
		html += "		<div style=\"padding-top: 5px;\"><span class=\"lableText\">Config Mode:&nbsp;</span><span class=\"text\">"+this.device.configModeName+"</span></div>";
		html += "		<div style=\"padding-top: 5px;\"><span class=\"lableText\">Ip Address:&nbsp;</span><span class=\"text\">"+this.device.ip+"</span></div>";		
		html += "		<div style=\"padding-top: 5px;\"><span class=\"lableText\">Created On:&nbsp;</span><span class=\"text\">"+this.device.creationStr+"</span></div>";
		html += "		<div style=\"padding-top: 5px;\"><span class=\"lableText\">Updated On:&nbsp;</span><span class=\"text\">"+this.device.updatedStr+"</span></div>";
		html += "		<div style=\"padding-top: 5px;\"><span class=\"lableText\">Last Contact On:&nbsp;</span><span class=\"text\">"+this.device.contactedStr+"</span></div>";
		html += "		<div style=\"padding-top: 5px;\"><span class=\"lableText\">License:&nbsp;</span><span class=\"text\">"+this.device.licenseID+"</span></div>";
		html += "		<div style=\"padding-top: 5px;\"><span class=\"lableText\">Description:&nbsp;</span><span class=\"text\">"+this.device.description+"</span></div>";
		if(this.device.actionPeriod.length == 0) {
			html += "		<div style=\"padding-top: 5px;\"><span class=\"lableText\">Operation time:&nbsp;</span><span class=\"text\">from 0:00 to 23:59</span></div>";
		} else {
			var begin = this.device.actionPeriod.substr(0,this.device.actionPeriod.indexOf(" "));
        	var end = this.device.actionPeriod.substr(this.device.actionPeriod.indexOf(" ")+1);
			html += "		<div style=\"padding-top: 5px;\"><span class=\"lableText\">Operation time:&nbsp;</span><span class=\"text\">from "+begin+" to "+end+"</span></div>";
		}
		
		if(this.commands) {
			if(this.commands.length > 0) {
				html += "	<div style=\"padding-top: 5px;\"><span class=\"lableText\">Override wan settings:&nbsp;</span><span class=\"text\">yes</span></div>";
				
				if(this.commands[0].action == 'enableInternetDhcp') {
					html += "<div style=\"padding: 5px 0px 0px 10px;\"><span style=\"font-size: 11px;\" class=\"lableText\">Connection Mode:&nbsp;</span><span style=\"font-size: 11px;\" class=\"text\">dhcp</span></div>";
					if(this.commands.length == 2 && this.commands[1].args[0] != "0") {
						html += "<div style=\"padding: 5px 0px 0px 10px;\"><span style=\"font-size: 11px;\" class=\"lableText\">Maximum Packet Size:&nbsp;</span><span style=\"font-size: 11px;\" class=\"text\">" +this.commands[1].args[0]+ " bytes</span></div>";
					}
    			} else if(this.commands[0].action == 'enableInternetStatic') {
					html += "<div style=\"padding: 5px 0px 0px 10px;\"><span style=\"font-size: 11px;\" class=\"lableText\">Connection Mode:&nbsp;</span><span style=\"font-size: 11px;\" class=\"text\">static</span></div>";
    				html += "<div style=\"padding: 5px 0px 0px 10px;\"><span style=\"font-size: 11px;\" class=\"lableText\">Ip Address:&nbsp;</span><span style=\"font-size: 11px;\" class=\"text\">"+this.commands[0].args[0]+"</span></div>";
    				html += "<div style=\"padding: 5px 0px 0px 10px;\"><span style=\"font-size: 11px;\" class=\"lableText\">Netmask:&nbsp;</span><span style=\"font-size: 11px;\" class=\"text\">"+this.commands[0].args[1]+"</span></div>";
    				html += "<div style=\"padding: 5px 0px 0px 10px;\"><span style=\"font-size: 11px;\" class=\"lableText\">Gateway:&nbsp;</span><span style=\"font-size: 11px;\" class=\"text\">"+this.commands[0].args[2]+"</span></div>";
    				html += "<div style=\"padding: 5px 0px 0px 10px;\"><span style=\"font-size: 11px;\" class=\"lableText\">Primary DNS:&nbsp;</span><span style=\"font-size: 11px;\" class=\"text\">"+this.commands[0].args[3]+"</span></div>";
    				if(this.commands[0].args.length > 4)
    					html += "<div style=\"padding: 5px 0px 0px 10px;\"><span style=\"font-size: 11px;\" class=\"lableText\">Secondary DNS:&nbsp;</span><span style=\"font-size: 11px;\" class=\"text\">"+this.commands[0].args[4]+"</span></div>";
					if(this.commands.length == 2 && this.commands[1].args[0] != "0") {
						html += "<div style=\"padding: 5px 0px 0px 10px;\"><span style=\"font-size: 11px;\" class=\"lableText\">Maximum Packet Size:&nbsp;</span><span style=\"font-size: 11px;\" class=\"text\">" +this.commands[1].args[0]+ " bytes</span></div>";
					}
    			} else if(this.commands[0].action == 'enableInternetPppoe') {
    				html += "<div style=\"padding: 5px 0px 0px 10px;\"><span style=\"font-size: 11px;\" class=\"lableText\">Connection Mode:&nbsp;</span><span style=\"font-size: 11px;\" class=\"text\">pppoe</span></div>";
    				html += "<div style=\"padding: 5px 0px 0px 10px;\"><span style=\"font-size: 11px;\" class=\"lableText\">Username:&nbsp;</span><span style=\"font-size: 11px;\" class=\"text\">"+this.commands[0].args[0]+"</span></div>";
    			
    				for(var i=1; i<this.commands.length; i++) {
    					if(this.commands[i].action == 'setInternetIpAddress' && this.commands[i].args[0] != "auto") {
							html += "<div style=\"padding: 5px 0px 0px 10px;\"><span style=\"font-size: 11px;\" class=\"lableText\">Ip Address:&nbsp;</span><span style=\"font-size: 11px;\" class=\"text\">" +this.commands[i].args[0]+ "</span></div>";    						
    					} else if(this.commands[i].action == 'setInternetGateway' && this.commands[i].args[0] != "auto") {
							html += "<div style=\"padding: 5px 0px 0px 10px;\"><span style=\"font-size: 11px;\" class=\"lableText\">Gateway:&nbsp;</span><span style=\"font-size: 11px;\" class=\"text\">" +this.commands[i].args[0]+ "</span></div>";    						
    					} else if(this.commands[i].action == 'setInternetDNS' && this.commands[i].args[0] != "auto") {
							html += "<div style=\"padding: 5px 0px 0px 10px;\"><span style=\"font-size: 11px;\" class=\"lableText\">Primary DNS:&nbsp;</span><span style=\"font-size: 11px;\" class=\"text\">" +this.commands[i].args[0]+ "</span></div>";    						
							html += "<div style=\"padding: 5px 0px 0px 10px;\"><span style=\"font-size: 11px;\" class=\"lableText\">Secondary DNS:&nbsp;</span><span style=\"font-size: 11px;\" class=\"text\">" +this.commands[i].args[1]+ "</span></div>";    						
    					} else if(this.commands[i].action == 'setInternetVlanValue' && this.commands[i].args.length != 0) {
							html += "<div style=\"padding: 5px 0px 0px 10px;\"><span style=\"font-size: 11px;\" class=\"lableText\">VLAN:&nbsp;</span><span style=\"font-size: 11px;\" class=\"text\">" +this.commands[i].args[0]+ "</span></div>";
    					} else if(this.commands[i].action == 'setInternetMTUValue' && this.commands[i].args[0] != "0") {
							html += "<div style=\"padding: 5px 0px 0px 10px;\"><span style=\"font-size: 11px;\" class=\"lableText\">Maximum Packet Size:&nbsp;</span><span style=\"font-size: 11px;\" class=\"text\">" +this.commands[i].args[0]+ " bytes</span></div>";
    					}    					
    				}
      			}				
				
			} else {
				html += "	<div style=\"padding-top: 5px;\"><span class=\"lableText\">Override wan settings:&nbsp;</span><span class=\"text\">no</span></div>";
			}
		}
		html += "	</div>"
		
		if(this.device.lastRestore != 0) {
			html += "	<div style=\"padding: 15px 0px 0px 10px;\">"
			html += "		<span class='subheadText'>Current Device Configuration</span>"
			html += "		<div style=\"padding-top: 5px;\"><span class=\"lableText\">Configuration:&nbsp;</span><span class=\"text\">"+this.device.lastRestoreConfigName+"</span></div>";
			html += "		<div style=\"padding-top: 5px;\"><span class=\"lableText\">Last Contact On:&nbsp;</span><span class=\"text\">"+this.device.lastRestoreStr+"</span></div>";
			html += "	</div>"
		}
		
//		if(this.device.lastBackup != 0) {
//			html += "	<div style=\"padding: 15px 0px 0px 10px;\">"
//			html += "		<span class='subheadText'>Device Configuration Backup</span>"
//			html += "		<div style=\"padding-top: 5px;\"><span class=\"lableText\">Backup Date:&nbsp;</span><span class=\"text\">"+this.device.lastBackupStr+"</span></div>";
//			html += "		<div style=\"padding-top: 5px;\"><span class=\"lableText\">Backup File:&nbsp;</span><a href=\"/ACSInterface?license=" +  this.device.licenseID + "&backup=yes\" class=\"textLink\">download</a></div>";
//			html += "	</div>"
//		}
		
		if(this.device.contacted != 0) {
			html += "	<div style=\"padding: 15px 0px 0px 10px;\">"
			html += "		<span class='subheadText'>System Information</span>"
			html += "		<div style=\"padding-top: 5px;\"><span class=\"lableText\">Customer Name:&nbsp;</span><span class=\"text\">"+this.device.customerName+"</span></div>";
			html += "		<div style=\"padding-top: 5px;\"><span class=\"lableText\">Max Users:&nbsp;</span><span class=\"text\">"+this.device.maxUsers+"</span></div>";
			html += "		<div style=\"padding-top: 5px;\"><span class=\"lableText\">Release:&nbsp;</span><span class=\"text\">"+this.device.release+"</span></div>";
			html += "		<div style=\"padding-top: 5px;\"><span class=\"lableText\">Build:&nbsp;</span><span class=\"text\">"+this.device.build+"</span></div>";
			html += "		<div style=\"padding-top: 5px;\"><span class=\"lableText\">PEPs Version:&nbsp;</span><span class=\"text\">"+this.device.pepsVersion+"</span></div>";
			html += "		<div style=\"padding-top: 5px;\"><span class=\"lableText\">GUI Version:&nbsp;</span><span class=\"text\">"+this.device.guiVersion+"</span></div>";
			html += "		<div style=\"padding-top: 5px;\"><span class=\"lableText\">Up time:&nbsp;</span><span class=\"text\">"+this.device.upTime+"</span></div>";
			html += "		<div style=\"padding-top: 5px;\"><span class=\"lableText\">System Load:&nbsp;</span><span class=\"text\">"+this.device.systemLoad+"</span></div>";
			html += "		<div style=\"padding-top: 5px;\"><span class=\"lableText\">Installed Memory:&nbsp;</span><span class=\"text\">"+this.device.installedMemory+"</span></div>";
			html += "		<div style=\"padding-top: 5px;\"><span class=\"lableText\">Free Memory:&nbsp;</span><span class=\"text\">"+this.device.freeMemory+"</span></div>";
			html += "		<div style=\"padding-top: 5px;\"><span class=\"lableText\">Swap Used:&nbsp;</span><span class=\"text\">"+this.device.swapUsed+"</span></div>";
			html += "		<div style=\"padding-top: 5px;\"><span class=\"lableText\">Partition /:&nbsp;</span><span class=\"text\">"+this.device.partitionRoot+"</span></div>";
			html += "		<div style=\"padding-top: 5px;\"><span class=\"lableText\">Partition /var:&nbsp;</span><span class=\"text\">"+this.device.partitionVar+"</span></div>";
			html += "		<div style=\"padding-top: 5px;\"><span class=\"lableText\">Partition /home:&nbsp;</span><span class=\"text\">"+this.device.partitionHome+"</span></div>";
			html += "	</div>"
		}
		
		this.deviceInformation.update(html);
	},

	renderLogLevel : function(status){
		if(status == 0) { //ACS_LL_DEBUG
			return '<img src=icons/log-trace.png>';
		} else if(status == 1) { //ACS_LL_NOTICE
			return '<img src=icons/log-info.png>';
		} else if(status == 2) { //ACS_LL_WARNING
			return '<img src=icons/log-warning.png>';
		} else if(status == 3) { //ACS_LL_ERROR
			return '<img src=icons/log-error.png>';
		} else {
			return 'none';
		}
	}
});

Ext.reg('appdevicepanel', DevicePanel);